import { AppDataSource } from "../data-source";
import { NextFunction, Request, Response } from "express";
import { User } from "../entity/User";
import { jwtEncryptionVerify, jwtEncryptionSign } from "../utils/jwt.js";
import { encryptPassword, decodePassword } from "../utils/provide.js";

export class UserController {
  private userRepository = AppDataSource.getRepository(User);
  //   登录接口
  async usersLogin(request: Request, response: Response, next: NextFunction) {
    const { userName, passWord } = request.query;
    try {
      let result = await this.userRepository.findOne({
        where: { userName },
      });
      let plaintext = await decodePassword(passWord, result);
      if (plaintext) {
        response.json({
          code: "0000",
          data: {
            token: jwtEncryptionSign({
              userName,
              role: result.role,
            }),
          },
          msg: "登录成功",
        });
        return;
      }
    } catch (error) {
      console.log("登录接口报错了", error);
    }
  }
  // 注册用户
  async registerUser(request: Request, response: Response, next: NextFunction) {
    const { userName, email, passWord } = request.body;
    let passwordHash = await encryptPassword(passWord);
    const user = Object.assign(new User(), {
      userName,
      email,
      passwordHash,
    });
    try {
      let result = await this.userRepository.save(user);
      if (result) {
        response.json({
          code: "0000",
          data: {},
          msg: "注册成功",
        });
        return;
      }
    } catch (error) {
      console.log("注册接口报错了", error);
    }
  }
  // 查询用户接口
  async queryUser(request: Request, response: Response, next: NextFunction) {
    const userName = request.query.userName;
    let plaintext = jwtEncryptionVerify(
      request.headers["authorization"]?.split(" ")[1]
    );
    let users;
    if (plaintext.role != "admin") {
      return {
        code: "0005",
        msg: "抱歉您没有权限，请联系管理员",
        data: null,
      };
    }
    if (userName) {
      users = await this.userRepository.findOne({
        where: { userName },
      });
    } else {
      users = await this.userRepository.find();
    }
    if (!users) {
      return {
        code: "0001",
        msg: "未查到用户！",
        data: null,
      };
    }
    return {
      msg: "成功",
      code: "0000",
      data: {
        ...users,
      },
    };
  }
  // 删除用户
  async removeUser(request: Request, response: Response, next: NextFunction) {
    const { userName } = request.body;

    let userToRemove = await this.userRepository.findOne({
      where: { userName },
    });
    if (userToRemove.role == "admin") {
      return {
        code: "0006",
        msg: "该身份是管理员，如需删除请联系超级管理员",
        data: null,
      };
    }
    let plaintext = jwtEncryptionVerify(
      request.headers["authorization"]?.split(" ")[1]
    );
    if (plaintext.role != "admin" && userToRemove.role != "root") {
      return {
        code: "0005",
        msg: "抱歉您没有权限，请联系管理员",
        data: null,
      };
    }
    if (!userToRemove) {
      return {
        code: "0007",
        msg: "未查询到相关用户信息",
        data: null,
      };
    }
    try {
      await this.userRepository.remove(userToRemove);
      return {
        code: "0000",
        msg: "删除成功",
        data: null,
      };
    } catch (error) {
      return {
        code: "0000",
        msg: error,
        data: null,
      };
    }
  }
}
